import {messages} from "share/common";
import React from 'react'
import {connect} from 'react-redux'
import {Input, Button, Icon, Spin, notification, message, Form, Modal, Table} from 'antd';
import moment from 'moment'
import config from 'config'
import 'moment/locale/zh-cn';
import CheckCenterImporter from 'containers/financial-management/check-center/check-center-importer'
import common from 'containers/financial-management/check-center/check-common'
import checkCenterService from 'containers/financial-management/check-center/check-center.service'
import resizeTableService from "components/resize-table/resize-table.service";
import CheckUtil from 'containers/financial-management/check-center/check-util';
import CheckColumn from 'containers/financial-management/check-center/consumer-columns';
import CheckForm from 'containers/financial-management/check-center/check-search-form';
import 'styles/financial-management/check-center/check-center-bill.scss'

import Control from 'components/control';


class CheckCenterTicket extends React.Component {
  constructor(props) {
    super(props);
    this.advanceTable = null; //高级表格实例
    this.templateOffLineVendorTemplate = {
      "channel": "hly-admin",
      "key": props.params.type,
      tenantId: props.tenant.id,
    }
    this.uploadOption = {
      isReplace: true,
      descDownload: [
        `1.${messages('financial-management.key90'/*点击上方按钮*/)}`,
        `2.${messages('financial-management.key91'/*严格按照导入模板整理数据，检查必输事项是否缺少数据*/)}`,
        `3.${messages('financial-management.key852')/*确保需导入的消费商code已存在*/}`,
        <a onClick={() => this.controlCodeModal(true)}>{messages('financial-management.key853')/*查看现有消费商及导入code*/}</a>,
      ],
      descUpload: [
        `1.${messages('financial-management.key854')/*点击【上传文件】按钮，选择你需要导入的文件*/}`,
        `2.${messages('financial-management.key96'/*点击【导入】按钮*/)}`,
        <span style={{color: 'red'}}>3.{messages('financial-management.key855')/*导入完成前，请勿关闭此窗口*/}</span>
      ]
    };
    this.codeColumns = [
      {title: messages('common.sequence')/*序号*/, dataIndex: 'index'},
      {title: messages('financial-management.key856')/*消费商名称*/, dataIndex: 'vendorCn'},
      {title: messages('financial-management.key857')/*消费商导入code*/, dataIndex: 'vendor'},
    ]
    this.state = {
      loading: false,
      data: [],
      showConfirmBill: true,
      selectedRowKeys: [],
      confirmLoading: false,
      type: '',
      amount: 0,
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 20,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      searchParams: {},
      confirmParams: {
        channel: 'hly-admin',
        companyOID: '',
        endTime: '',
        journeyId: '',
        orderType: '',
        reconciliationStatus: '',
        recordId: '',
        recordIds: [],
        searchFlag: false,
        size: 20,
        startTime: '',
        vendorName: ''
      },
      showImportFrame: false,
      defaultLabel: '2',
      radio: common.getRadioMap(),
      searchForm: [],
      columns: [],
      offColumns: [],// 线下核对表格列配置项数据
      selectedData: [],
      rowSelection: {
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll,
        hideDefaultSelections: true,//去掉默认的
        selections: [{
          key: 'all-data',
          text: messages('setting.key195'),
          onSelect: this.selectAllData,
        },
          {
            key: 'cancel-data',
            text: messages('common.cancel')/*取消*/,
            onSelect: this.cancelSelectAllData,
          },
        ],
      },
      buttonRoleSwitch: this.checkPageRoleForOld('VENDORRECONCILIATION', 2),
      offLineCheckModel: false,// 线下对账模式
      uploading: false, // 线下核对开始上传
      startSetAttr: false, // 设置显示属性modal开关
      currentAllAttrs: [], // 当前消费商所有字段，也是可供选显示字段
      checkOffLineResult: {},// 线下核对结果
      checkOffLineResultArray: [], // 核对结果数组
      dataLength: 0, // 正常模式下数据总条数
      isTheSame: 0, //
      showOffLineData: false, // 是否导入线下消费数据
      idea: '',// 意见,
      codeSource: [], // 消费商code弹框表格数据
      showCode: false,// 是否显示消费商code弹框
      serverColumns: [],//接口返回的table列，包含hide参数的
    }
  }

  // wjk add select all
  selectAllData = () => {
    const {offLineCheckModel} = this.state;
    this.setState({loading: true});
    if (offLineCheckModel) {
      this.requestCheckResult(true);
    } else {
      this.notUnderOffLineCheckModel();
    }
  }

  notUnderOffLineCheckModel = () => {
    const {pagination, searchParams, type} = this.state;
    let selectedData = [];
    searchParams.page = 0;
    searchParams.size = pagination.total;
    searchParams.companyType = this.props.tenantMode ? '1002' : '1001',
      checkCenterService.getPlaneBill(searchParams, type).then((response) => {
        selectedData = response.data.reconciliationSearchVOs || [];
        this.setState({selectedData: selectedData}, () => {
          this.refreshRowSelection();
        });
        this.setState({loading: false});
      }).catch(err => {
        this.setState({loading: false});
      })
  }

  cancelSelectAllData = () => {
    this.setState({selectedData: []}, () => {
      this.refreshRowSelection();
    });
  }

  componentWillMount() {
    if (this.props.language.code === 'zh_cn') {
      moment.locale('zh-cn');
    } else {
      moment.locale('en-US');
    }
    const {params, company} = this.props;
    resizeTableService.getColumns(`onLineTableCenter${params.type}`)
      .then(res => {
        if (res.data.length) {
          this.setState({serverColumns: res.data})
        }
      });
    this.setState({searchParams: common.getSearchParams(params.type)});
    let {columns, offColumns} = this.state;
    columns = CheckColumn.getColumns(params.type, this.filterMoney);
    offColumns = CheckColumn.getOffLineColumns(params.type, this.filterMoney);
    checkCenterService.getSuppliers().then(res => {
      let searchForm = CheckForm.searchForm(params.type, params.option) || [];
      let searchParams = this.state.searchParams;
      let confirmParams = this.state.confirmParams;
      searchParams.companyOID = company.companyOID;
      confirmParams.companyOID = company.companyOID;
      confirmParams.companyType = this.props.tenantMode ? '1002' : '1001';
      searchParams.companyType = this.props.tenantMode ? '1002' : '1001';
      this.setState({
        searchForm: searchForm,
        searchParams,
        confirmParams,
        type: params.type,
        columns,
        offColumns
      })
    })
    const codeParams = {
      channel: "hly-admin",
      tenantId: company.tenantId,
      page: 1,
      size: 200,
      companyType: this.props.tenantMode ? '1002' : '1001',
    }
    checkCenterService.getVendorCode(codeParams).then(res => {
      if (res.data.invoicePushConfigs) {
        res.data.invoicePushConfigs.map((item, index) => {
          item.index = index + 1;
        })
      }
      this.setState({codeSource: res.data.invoicePushConfigs});
    })
  }

  getAmount(params, type) {
    if (type === 'yget') {
      type = 'phone';
    }
    checkCenterService.getAmount(params, type).then(res => {
      this.setState({amount: res.data})
    })
  }

  onRadioChange = (e) => {
    let value = e.target.value
    let {pagination} = this.state;
    pagination.current = 1;
    value === '2'|| value === '3'? this.setState({showConfirmBill: true}) : this.setState({showConfirmBill: false});
    let searchParams = this.state.searchParams;
    searchParams.reconciliationStatus = value;
    this.setState({
      searchParams: searchParams,
      selectedData: [],
      pagination,
    }, () => {
      this.advanceTable.getList();
    })
  }

  getList = (page, size, searchValues) => {
    const {type, searchParams} = this.state;
    let isAdmin = (~this.props.user.authorities.indexOf('ROLE_COMPANY_FINANCE_ADMIN') ? true : false);
    if (!isAdmin) {
      this.setState({rowSelection: null});
    }
    searchParams.page = page;
    searchParams.size = size;
    searchParams.companyType = this.props.tenantMode ? '1002' : '1001';
    let params = Object.assign({}, searchParams, searchValues);
    this.setState({searchParams: params});
    this.getAmount(params, type);
    return checkCenterService.getPlaneBill(params, type).then(response => {
      if (response.data.reconciliationSearchVOs) {
        response.data.rows = response.data.reconciliationSearchVOs;
      }
      return response;
    });
  }

  advanceTableServer = (page, size, searchValues, status) => {
    const {offLineCheckModel} = this.state;
    if (offLineCheckModel) {
      return this.requestCheckResult(false, page+1, size);
    } else {
      return this.getList(page, size, searchValues);
    }
  }

  advanceTableRef = (advanceTable) => {
    this.advanceTable = advanceTable;
  }

  advanceTableFooter = () => {
    const {searchParams, selectedData, idea} = this.state;
    const dis = selectedData.length === 0;
    if (searchParams.reconciliationStatus === '2') {
      return (
        <Control>
          <span data-control="check-center.hidden">
            <Input
              placeholder={messages('financial-management.key923')/*意见，最多输入200个字符*/}
              maxLength={200}
              onChange={this.onIdeaChange}
              value={idea}
              style={{width: 246}}
            />
            <Button onClick={this.confirmBill} type='primary' disabled={dis}>{messages('components.key455'/*确认*/)}</Button>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            {CheckUtil.renderMoreSelect(this.onMoreOperator, dis)}
          </span>
        </Control>
      )
    } else {
      return false;
    }
  }

  advanceTableOnGetData = (dataSource, {total, page, pageSize}) => {
    const {pagination} = this.state;
    let isAdmin = (~this.props.user.authorities.indexOf('ROLE_COMPANY_FINANCE_ADMIN') ? true : false);
    pagination.total = total;
    pagination.page = total;
    pagination.pageSize = total;
    pagination.current = page;
    this.setState({pagination, data: dataSource}, () => {
      isAdmin && this.refreshRowSelection();
    });
  }

  // 监听意见输入框
  onIdeaChange = (eve) => {
    this.setState({idea: eve.target.value});
  }

  // 线下消费数据导入开启和关闭
  openUploadOffLineData = (isOpen) => {
    this.setState({showOffLineData: isOpen});
  }

  // 导入线下消费数据完成回调
  uploadOffLineDataFinish = () => {
    this.openUploadOffLineData(false);
    this.advanceTable.getList();
  }

  /**
   * 添加或取消标记
   * @param key  标记key值 addMark
   */
  onMoreOperator = ({key}) => {
    const {type, rowSelection, idea} = this.state;
    const params = {
      opinionMsg: idea || '',
      recordIds: rowSelection.selectedRowKeys,
      flag: true,
      channel: "hly-admin",
      vendorType: type,
      companyType: this.props.tenantMode ? '1002' : '1001'
    }
    if (key === 'addMark') {// 增加标记
      checkCenterService.addAndSubRemark(params).then(res => {
        if (res.status === 200) {
          this.advanceTable.getList();
        } else {
          message.error('error');
        }
      }).catch(err => {
        message.error(err.response.data.message);
      })
    } else {// 取消标记
      params.flag = false;
      checkCenterService.addAndSubRemark(params).then(res => {
        if (res.status === 200) {
          this.advanceTable.getList();
        } else {
          message.error('error');
        }
      }).catch(err => {
        message.error(err.response.data.message);
      })
    }
    this.clearRowSelection();
  }

  //清空选择框
  clearRowSelection() {
    const { rowSelection } = this.state;
    rowSelection.selectedRowKeys = [];
    this.setState({selectedData: [], rowSelection, idea:''});
  }

  //提交成功
  confirmSuccess(length, msg) {
    const {offLineCheckModel} = this.state;
    notification.open({
      message: msg ? messages('financial-management.key71'/*确认付款失败*/) : messages('financial-management.key70'/*确认账单成功*/),
      description: msg || messages('financial-management.key561', {arg1: length}),
      icon: <Icon type="smile-circle" className='default-color-font'/>,
      duration: 2,
    });
    this.clearRowSelection();
    this.advanceTable.getList();
  }

  //确认账单
  confirmBill = () => {
    this.setState({loading: true});
    let {selectedData, confirmParams, type, offLineCheckModel, checkOffLineResult, idea} = this.state;
    confirmParams.recordIds = [];
    selectedData.map(item => {
      confirmParams.recordIds.push(item.recordId)
    })
    if (offLineCheckModel) {
      confirmParams.redisKey = checkOffLineResult.key;
    }
    confirmParams.companyType = this.props.tenantMode ? '1002' : '1001';
    confirmParams.confirmSuggestion = idea || '';
    checkCenterService.confirmBill(confirmParams, type).then(res => {
      this.setState({loading: false});
      if (res.data.responseCode === '200') {
        this.confirmSuccess(selectedData.length);
      } else {
        this.confirmSuccess(selectedData.length, res.data.responseMessage);
      }
    }).catch(e => {
      this.setState({loading: false});
      if (e.name == 'SyntaxError')
        this.confirmSuccess();
      else
        notification.open({
          message: messages('financial-management.key71'/*确认付款失败*/),
          description: messages('financial-management.key72'/*可能是服务器出了点问题*/) + ':(',
          icon: <Icon type="frown-circle" style={{color: '#e93652'}}/>,
          duration: 2,
        });
    })
  }

  //列表选择更改
  onSelectChange = (selectedRowKeys) => {
    let {rowSelection} = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({rowSelection});
  };

  //全选
  onSelectAll = (selected, selectedRows, changeRows) => {
    changeRows.map(changeRow => this.onSelectItem(changeRow, selected));
  };

  onSelectItem = (record, selected) => {
    let {selectedData} = this.state;
    if (!selected) {
      selectedData.map((item, index) => {
        if (item.recordId === record.recordId) {
          selectedData.splice(index, 1)
        }
      })
    } else {
      selectedData.push(record)
    }
    this.setState({selectedData})
  };

  refreshRowSelection() {
    let {selectedData, rowSelection} = this.state;
    let nowSelectedRowKeys = [];
    selectedData.map(selected => {
      nowSelectedRowKeys.push(selected.recordId)
    });
    rowSelection.selectedRowKeys = nowSelectedRowKeys;
    this.setState({rowSelection});
  }

  showImport = (flag) => {
    this.setState({showImportFrame: flag})
  };

  //导入成功回调
  handleImportOk = () => {
    this.showImport(false);
    this.advanceTable.getList()
  };

  //下载账单
  downloadBill = () => {
    const {searchParams, type} = this.state;
    let hide = message.loading(messages('financial-management.key73'/*正在下载账单*/) + '..');
    checkCenterService.download(searchParams, type).then(res => {
      if (res.data.exportFileRecord.tempUrl) {
        window.open(res.data.exportFileRecord.tempUrl);
      }
      hide();
      this.advanceTable.getList();
    })
  }

  // 开启关闭线下核对模式
  startOffLine = (isClose) => {
    const {pagination} = this.advanceTable.state;
    pagination.current = 1;
    this.advanceTable.setState({pagination, dataSource: []})
    if (isClose) {
      this.setState({
        offLineCheckModel: false,
        selectedData: [],
      })
    } else {
      this.setState({
        offLineCheckModel: true,
        selectedData: [],
      })
    }
  }

  handleUpload = () => {
    this.setState({uploading: true});
  }

  finishUpload = (result) => {
    if (result.data) {
      this.setState({
        uploading: false,
        checkOffLineResult: result.data || {},
      }, () => {
        if (this.state.checkOffLineResult.key) {
          this.advanceTable.getList();
        } else {
          message.error(this.state.checkOffLineResult.responseMessage);
        }
      });
    } else {
      this.setState({
        uploading: false,
      })
    }
  }

  // 查询线下核对结果
  requestCheckResult(isSelectAll, page, size) {
    const {checkOffLineResult, pagination, isTheSame} = this.state;
    const params = {
      "channel": "hly-admin",
      "key": checkOffLineResult.key,
      "page": isSelectAll ? 1 : page,
      "size": isSelectAll ? pagination.total : size,
      companyType: this.props.tenantMode ? '1002' : '1001',
    }
    if (isTheSame === 1) {
      params.matching = true;
    } else if (isTheSame === 2) {
      params.matching = false;
    }
    return checkCenterService.requestCheckResult(params).then(res => {
      res.data.rows = res.data.contrastOrderList || [];
      res.data.total = res.data.total === null ? 0 : res.data.total;
      if (isSelectAll) {
        let selectedData = res.data.contrastOrderList || [];
        this.setState({selectedData: selectedData, loading: false}, () => {
          this.refreshRowSelection();
        });
      } else {
        this.setState({
          loading: false,
          checkOffLineResultArray: res.data.contrastOrderList || [],
        }, () => {
          this.refreshRowSelection();
        });
      }
      return res;
    }).catch(err => {
      message.error(err);
    })
  }

  // 下载核对结果
  downloadCheckResult = () => {
    const {checkOffLineResult} = this.state;
    const option = {
      companyType: this.props.tenantMode ? '1002' : '1001',
      key: checkOffLineResult.key,
    };
    common.downloadResultFile(option);
  }

  // 下载核对模板
  downloadOffLineTemplate = () => {
    const {type} = this.state;
    const option = {
      companyType: this.props.tenantMode ? '1002' : '1001',
      key: type,
    };
    common.downloadTemplateFile(option);
  }

  openSetAttr = () => {
    this.setState({startSetAttr: true});
  }

  // 是否一致
  isTheSameResult = (values) => {
    let res = 0;
    if (values.length === 1) {
      if (values[0] === '1') {
        res = 1;
      } else {
        res = 2;
      }
    }
    this.setState({isTheSame: res}, () => {
      this.advanceTable.getList();
    });
  }

  controlCodeModal = (flag) => {
    this.setState({showCode: flag})
  }

  // 下载导入线下消费商数据模板
  downloadVendorDataTemplate = (res) => {
    window.open(res.data.exportFileRecord.path);
  }

  render() {
    const {showImportFrame, loading, type, offLineCheckModel, showOffLineData} = this.state;
    const {showCode, codeSource} = this.state;
    const {tenantMode, company} = this.props;
    return (
      <Spin spinning={loading}>
        <div className="check-center-ticket" ref='controllView'>
          {false && !offLineCheckModel && CheckUtil.statusTabRow(this)}
          {!offLineCheckModel && CheckUtil.getOperatorRow(this)}
          {
            offLineCheckModel &&
            <div>
              {CheckUtil.uploadSteps(this)}
              {CheckUtil.uploadResult(this)}
            </div>
          }
          <div className='advance-table-height'>
            {CheckUtil.checkCenterTable(this)}
          </div>
          {/*批量确认*/}
          <CheckCenterImporter
            visible={showImportFrame}
            params={{companyType: tenantMode ? '1002' : '1002',}}/*暂时默认都是1002，后面会改回1001*/
            title={messages('financial-management.key78'/*对账状态导入*/)}
            templateUrl={`${config.baseUrl}/vendor-data-service/api/air/ctrip/reconciliation/import/template/v2`}
            uploadUrl={`${config.baseUrl}/vendor-data-service/api/order/reconciliation/import/${type}/v2?language=zh_cn`}
            fileName="Reconciliation Template"
            onOk={this.handleImportOk}
            afterClose={() => this.showImport(false)}
          />
          {/*导入线下消费数据(仅机票)*/}
          <CheckCenterImporter
            visible={showOffLineData}
            params={{companyType: tenantMode ? '1002' : '1002',}}/*暂时默认都是1002，后面会改回1001*/
            title={messages('financial-management.key858')/*导入线下消费商数据*/}
            templateUrl={`${config.baseUrl}/vendor-data-service/api/order/settlement/import/template`}
            uploadUrl={`${config.baseUrl}/report/api/order/reconciliation/import/${type}/v2?language=zh_cn`}
            fileName="Reconciliation Template"
            onOk={this.uploadOffLineDataFinish}
            afterClose={() => this.openUploadOffLineData(false)}
            {...this.uploadOption}
            templateMethod='post'
            templateParams={this.templateOffLineVendorTemplate}
            templateCallBack={this.downloadVendorDataTemplate}
          />
          <Modal
            visible={showCode}
            onOk={() => this.controlCodeModal(false)}
            onCancel={() => this.controlCodeModal(false)}
            title={messages('financial-management.key853')/*查看现有消费商及导入code*/}
          >
            <Table
              columns={this.codeColumns}
              dataSource={codeSource}
            />
          </Modal>
        </div>
      </Spin>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    language: state.main.language,
    user: state.login.user,
    tenantMode: state.main.tenantMode,
    tenant: state.login.tenant,
  }
}

const wrapperCheckCenterTicket = Form.create()(CheckCenterTicket);
export default connect(mapStateToProps)(wrapperCheckCenterTicket);
